package cn.com.shuyangyang.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.shuyangyang.controller.response.EmptyResponse;
import cn.com.shuyangyang.controller.response.ExceptionResponse;
import cn.com.shuyangyang.controller.response.NormalResponse;
import cn.com.shuyangyang.controller.response.Response;
import cn.com.shuyangyang.domain.Dept;
import cn.com.shuyangyang.domain.EnumStatus;
import cn.com.shuyangyang.domain.UserDept;
import cn.com.shuyangyang.service.DeptService;
import cn.com.shuyangyang.service.UserDeptService;

@Controller
@RequestMapping("/userdept/")
public class UserDepartmentController {

	Logger	logger	= LoggerFactory.getLogger(UserDepartmentController.class);

	@Autowired
	private UserDeptService	userDeptService;

	@Autowired
	private DeptService		deptService;

	/**
	 * 添加用户部门
	 * 
	 * @return
	 */
	@RequestMapping("addUserDept")
	@ResponseBody
	public Response addUserDept(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String userId = req.getParameter("userId");
			String dpetIds = req.getParameter("deptIds");
			String[] deptId = dpetIds.split(",");
			// 先删除之前保存的关联，重新保存勾选的
			userDeptService.deleteByUserId(userId);
			for (int i = 0; i < deptId.length; i++) {
				UserDept userDept = new UserDept();
				userDept.setUser_id(userId);
				userDept.setDept_id(deptId[i]);
				userDept.setCreate_time(new Date());
				userDept.setStatus(EnumStatus.AVAILABLE);
				userDeptService.saveUserDept(userDept);
			}
		} catch (Exception e) {
			logger.error("添加用户部门数据错误:" + e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
		return new NormalResponse();
	}

	/**
	 * 通过用户ID获取部门信息
	 * 
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping("findDeptInfoByUserId")
	@ResponseBody
	public Response findDeptInfoByUserId(HttpServletRequest req,
			HttpServletResponse resp) {
		try {
			String userId = req.getParameter("userId");
			List<Dept> depts = deptService.findDeptByUserId(userId);
			if (depts.size() > 0) {
				logger.debug("now {}", "返回用户数据。。。");
				return new NormalResponse(depts);
			} else {
				logger.debug("now {}", "用户数据为空！");
				return new EmptyResponse("用户获取部门数据");
			}
		} catch (Exception e) {
			logger.error("根据用户获取部门数据错误:" + e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}

	}
}
